﻿using System;
using System.Text;
using System.Collections.Generic;

namespace MySqlManager.DatabaseBuilder
{
    /// <summary>
    /// Indicates that is possible to create a MySQL database table from the class
    /// </summary>
    public class MySqlFieldAttribute : Attribute
    {
        /// <summary>
        /// True if the column will implement the AutoIncrement feature
        /// </summary>
        public bool AutoIncrement = false;

        /// <summary>
        /// Sets the default value for the column
        /// </summary>
        public object Default;

        /// <summary>
        /// True if the column will accept null values
        /// </summary>
        public bool Nullable = true;

        /// <summary>
        /// True if the column will be the primary key of the table
        /// </summary>
        public bool IsPrimaryKey = false;

        /// <summary>
        /// Gets or sets the name for the new column
        /// </summary>
        internal string ColumnName { get; set; }

        /// <summary>
        /// Gets the type of the value with this attribute
        /// </summary>
        internal Type VariableType;

        /// <summary>
        /// Initializes a new instance of the <see cref="MySqlFieldAttribute"/> class
        /// </summary>
        /// <param name="fieldName">Name that will take the new column</param>
        public MySqlFieldAttribute(string fieldName)
        {
            this.ColumnName = fieldName;
        }

        /// <summary>
        /// Override of the object.ToString() method
        /// </summary>
        /// <returns>Returns the column data structured as query</returns>
        public override string ToString()
        {
            StringBuilder columnBuilder = new StringBuilder();
            columnBuilder.AppendFormat("`{0}` ", this.ColumnName);
            columnBuilder.Append(SupportedTypesDictionary.GetTypeMeaning(this.VariableType));

            if (this.Nullable)
            {
                columnBuilder.Append(" NULL");
            }
            else
            {
                columnBuilder.Append(" NOT NULL");
            }
            if (this.Default != null && !(
                SupportedTypesDictionary.GetTypeMeaning(VariableType).Contains("text")
                ||SupportedTypesDictionary.GetTypeMeaning(VariableType).Contains("text")))
            {
                columnBuilder.Append(" default ");
                columnBuilder.AppendFormat("'{0}'", this.Default);
            }
            if (this.AutoIncrement)
            {
                columnBuilder.Append(" AUTO_INCREMENT");
            }

            return columnBuilder.ToString();
        }
    }
}
